<template>
  <div class="add-keyperson-dialog">
   <el-form :inline="true"
        ref="addKeyPersonForm"
        :model="addKeyPersonForm"
        class="demo-form-inline"
        label-width="1.4rem"
        :rules="rules">
    <el-form-item label="姓名：" prop="name">
     <el-input style="width:1rem;" v-model="addKeyPersonForm.name" placeholder="请输入姓名"></el-input>
    </el-form-item>
    <el-form-item label="性别：" label-width="0.64rem" prop="sex">
     <el-select style="width:0.65rem;" v-model="addKeyPersonForm.sex" placeholder="请选择">
      <el-option label="男" value="1"></el-option>
      <el-option label="女" value="2"></el-option>
     </el-select>
    </el-form-item>
    <el-form-item label="年龄：" label-width="0.64rem" prop="age">
     <el-input style="width:0.65rem;" v-model="addKeyPersonForm.age" placeholder="请输入"></el-input>
    </el-form-item>
    <el-form-item prop="file" class="upload-img-form" ref="uploadElement">
     <el-upload class="upload-img"
           :style="{backgroundImage:'url(' + dialogImageUrl + ')', backgroundRepeat:'no-repeat', backgroundPosition:'center center', backgroundSize: 'contain'}"
           ref="uploadxls"
           action="aaa"
           ::limit="1"
           :show-file-list="false"
           :on-change="handlePictureCardPreview"
           :before-upload="beforeupload"
           accept="image/png,image/gif,image/jpg,image/jpeg">
      <i v-show="!dialogImageUrl" class="el-icon-upload avatar-uploader-icon"></i>
      <div v-show="!dialogImageUrl" slot="tip" class="el-upload__text upload__tip">上传照片</div>
     </el-upload>
    </el-form-item>
    <!--<img :src="dialogImageUrl"/>-->
   </el-form>
  </div>
</template>
<script>
import PersonnelControlAdd from "./PersonnelControlAdd.vue"
import axiosControl from "./../../api/control"
import PersonnelAddPosition from "./PersonnelAddPosition.vue"
export default {
  components: {
    PersonnelAddPosition,
    PersonnelControlAdd},
  name: "add-keyperson-dialog",
  props: {
    dialogType: {
      type: String
    },
    keypersonList: {
      type: Object
    }
  },
  computed: {
    position: { // 经纬度
      // getter
      get: function () {
        let str = ""
        if (this.addKeyPersonForm.longitude !== "" && this.addKeyPersonForm.latitude !== "" && this.addKeyPersonForm.longitude !== null && this.addKeyPersonForm.latitude !== null) {
          str = this.addKeyPersonForm.longitude + "," + this.addKeyPersonForm.latitude
        }
        return str
      },
      // setter
      set: function (newValue) {
      }
    }
  },
  /* watch: {
  keypersonList: { // 深度监听，可监听到对象、数组的变化
   handler (newQuestion, oldQuestion) {
    this.addKeyPersonForm = Object.assign({}, this.keypersonList)
    this.dialogImageUrl = Object.assign({}, this.keypersonList).iconUrl
   },
   deep: true
  }
 }, */
  data () {
    return {
      doSubmitFlag: false,
      showPosition: false,
      doUpload: false,
      addKeyPersonForm: Object.assign({}, this.keypersonList),
      positionForm: {
        longtitude: this.keypersonList.longitude,
        latitude: this.keypersonList.latitude
      },
      dialogImageUrl: Object.assign({}, this.keypersonList).iconUrl, // 图片
      formData: new FormData(),
      rules: { // 表单验证
        name: [
          { required: true, message: "必填项", trigger: "blur" }
        ],
        age: [
          { required: true, message: "必填项", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "必填项", trigger: ["blur", "change"] }
        ],
        nationlity: [
          { required: true, message: "必填项", trigger: ["blur", "change"] }
        ],
        userType: [
          { required: true, message: "必填项", trigger: ["blur", "change"] }
        ],

        registered: [
          { required: true, type: "array", message: "必填项", trigger: ["blur", "change"] }
        ],
        registeredDetails: [
          { required: true, message: "必填项", trigger: "blur" }
        ],
        domicile: [
          { required: true, type: "array", message: "必填项", trigger: ["blur", "change"] }
        ],
        domicileDetails: [
          { required: true, message: "必填项", trigger: "blur" }
        ],
        file: [
          { required: true, message: "请上传图片" }
        ]
      }
    }
  },
  created () {
    this.getKeyPersonType()
  },
  methods: {
    handleChange (value) {
    },
    // 图片预览
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.addKeyPersonForm.file = file.url
      this.doUpload = true
      this.$refs["addKeyPersonForm"].validateField("file")
    },
    // 阻止upload的自己上传，进行再操作
    beforeupload (file) {
      this.formData.append("file", file)
      return false
    },
    // 上传重点人员信息
    onSubmit: function () {
      let that = this
      that.formData = new FormData()
      that.rules.file = [{ required: true, message: "请上传图片" }]
      if (that.dialogType !== "add" && !this.doUpload) {
        that.rules.file = []
        that.$refs["uploadElement"].clearValidate()
      }
      that.$refs["addKeyPersonForm"].validate((valid) => {
        if (valid) {
          that.formData.append("name", that.addKeyPersonForm.name)
          if (that.addKeyPersonForm.sex === "男") {
            that.addKeyPersonForm.sex = 1
          } else if (that.addKeyPersonForm.sex === "女") {
            that.addKeyPersonForm.sex = 2
          }
          that.formData.append("sex", that.addKeyPersonForm.sex)
          that.formData.append("age", that.addKeyPersonForm.age)
          that.formData.append("idCard", that.addKeyPersonForm.idCard)
          that.formData.append("nationlity", that.addKeyPersonForm.nationlity)
          that.formData.append("plateNumber", that.addKeyPersonForm.plateNumber)
          that.formData.append("userType", that.addKeyPersonForm.userType)
          that.formData.append("longitude", that.addKeyPersonForm.longitude)
          that.formData.append("latitude", that.addKeyPersonForm.latitude)
          that.formData.append("registered", that.addKeyPersonForm.registered.join("-"))
          that.formData.append("registeredDetails", that.addKeyPersonForm.registeredDetails)
          that.formData.append("domicile", that.addKeyPersonForm.domicile.join("-"))
          that.formData.append("domicileDetails", that.addKeyPersonForm.domicileDetails)
          that.formData.append("problem", that.addKeyPersonForm.problem)
          that.formData.append("measure", that.addKeyPersonForm.measure)
          that.formData.append("controller", JSON.stringify(that.addKeyPersonForm.controller))
          that.formData.append("remark", that.addKeyPersonForm.remark)
          if (that.dialogType === "add") {
            that.$refs.uploadxls.submit() // 提交时触发了before-upload函数
            that.doSubmitFlag = true
            axiosControl.saveNewKeyPerson(that.formData)
              .then(res => {
                that.doSubmitFlag = false
                if (res.data.code === 200) {
                  that.$message({
                    type: "success",
                    message: "添加成功"
                  })
                  that.$refs.addKeyPersonForm.dialogImageUrl = "none"
                  that.$refs.uploadxls.clearFiles()
                  that.$refs.addKeyPersonForm.resetFields()
                  that.fileName = ""
                  that.uploadForm = new FormData()
                  that.$emit("savePersonSuccess")
                } else {
                  that.$message.error({
                    message: res.data.message
                  })
                }
              })
            /* .catch(err => {
        that.$message.error({
         message: err
        })
       }) */
          } else {
            if (!that.doUpload) {
              that.formData.append("iconUrl", that.addKeyPersonForm.iconUrl)
            }
            // 还要传id
            that.formData.append("id", that.addKeyPersonForm.id)
            that.doSubmitFlag = true
            axiosControl.saveEditKeyPerson(that.formData)
              .then(res => {
                that.doSubmitFlag = false
                if (res.data.code === 200) {
                  that.$message({
                    type: "success",
                    message: "添加成功"
                  })
                  that.$refs.addKeyPersonForm.dialogImageUrl = "none"
                  that.$refs.uploadxls.clearFiles()
                  that.$refs.addKeyPersonForm.resetFields()
                  that.fileName = ""
                  that.uploadForm = new FormData()
                  that.$emit("savePersonSuccess")
                } else {
                  that.$message.error({
                    message: res.data.message
                  })
                }
              })
          }
        } else {
          this.$message({
            type: "warning",
            message: "请填写正确格式"
          })
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
 .add-keyperson-dialog{
  position:relative;
  height:7.2rem;
  overflow:auto;
 }
 .add-keyperson-dialog .demo-form-inline{
  font-size:0.13rem;
  color:#666;
 }
 /*上传图片样式*/
 .add-keyperson-dialog .upload-img-form{
  width: 1rem;
  height: 1.35rem;
  position: absolute;
  right:0.2rem;
  top:0rem;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  text-align: center;
 }
 .add-keyperson-dialog .upload-img{
  width: 1rem;
  height: 1.35rem;
  overflow:hidden;
 }
 .add-keyperson-dialog .upload-img:hover {
  border-color: #409EFF;
  color: #409EFF;
 }
 .add-keyperson-dialog .avatar-uploader-icon {
  position:relative;
  z-index:100;
  font-size: 0.3rem;
  color: #8c939d;
  width: 0.9rem;
  height: 1.35rem;
  line-height: 1rem;
  text-align: center;
 }
 .add-keyperson-dialog .upload-img:hover .avatar-uploader-icon {
  color: #409EFF
 }
 .add-keyperson-dialog .avatar {
  width: 100%;
  height: auto;
  display: block;
 }
 .add-keyperson-dialog .upload__tip {
  font-size: 0.13rem;
  text-align: center;
  position: relative;
  z-index:10;
  top: -0.7rem;
 }
</style>
